﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Core.Helpers;
using MvcEngine.Core.Configuration;

using System.Net.Mail;
using System.Threading;
using MvcEngine.Core.Localization;
using System.Net;

namespace MvcEngine.Core.Services
{
    public class EmailSender : IEmailSender
    {
        private readonly bool enableSsl;

        public static IEmailSender Current
        {
            get { return IoC.Resolve<IEmailSender>(); }
        }

        public EmailSender(bool enableSsl)
        {
            this.enableSsl = enableSsl;
        }

        public void SendMail(EmailSettings settings, MailMessage mail)
        {
            try
            {
                SmtpClient smtp = new SmtpClient
                {
                    EnableSsl = enableSsl,
                    Host = settings.Host,
                    Port = settings.Port,
                    Credentials = new NetworkCredential(settings.UserName, settings.Password)
                };
                smtp.Send(mail);
            }
            catch (Exception e)
            {
                string msg = string.Format("<br/>Subject: {0};<br/>Body: {1};<br/>From: {2};<br/>To: {3}", mail.Subject, mail.Body, mail.From.Address, mail.To[0].Address);
                LogHelper.Current.WriteError(e.Message + msg, e);
                throw;
            }
        }

        public virtual void SendMailAsync(EmailSettings settings, string fromAddress, string toAddress, string subject, string body)
        {
            ThreadPool.QueueUserWorkItem(state => SendMail(settings, fromAddress, toAddress, subject, body));
        }

        public virtual void SendMail(EmailSettings settings, string fromAddress, string toAddress, string subject, string body)
        {
            using (MailMessage mail = BuildMessage(settings, fromAddress, toAddress, subject, body))
            {
                SendMail(settings, mail);
            }
        }

        public virtual string GetMailBody(string resourceKey, params string[] pairs)
        {
            string body = ResourceReader.Current.GetString(resourceKey);

            for (var i = 0; i < pairs.Length; i += 2)
            {
                body = body.Replace(string.Format("<%={0}%>", pairs[i]), pairs[i + 1]);
            }
            return body;
        }

        protected virtual MailMessage BuildMessage(EmailSettings settings, string fromAddress, string toAddress, string subject, string body)
        {
            MailMessage message = new MailMessage
            {
                Sender = new MailAddress(settings.Email), // on Behave of When From differs
                From = new MailAddress(fromAddress),
                Subject = subject,
                Body = body,
                IsBodyHtml = true,
            };

            string[] tos = toAddress.Split(';');

            foreach (string to in tos)
            {
                string mail = to.Trim();
                if (!string.IsNullOrEmpty(mail))
                    message.To.Add(new MailAddress(to));
            }

            return message;
        }
    }
}
